package org.walker.iotScheduling.modules.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author :zhuangguojin
 * @since :2024/12/3 17:08
 */
@Configuration
public class ThreadPoolTaskExecutorConfig {

    @Bean("ThreadPoolExecutorCommon")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(50);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("MyThreadPoolTaskExecutor-");
        executor.setRejectedExecutionHandler((runnable, e) -> {
            throw new SecurityException("This threadPool is busy!");
        });
        executor.initialize();
        return executor;
    }

    public static void main(String[] args) {
        // 当线程池中的核心线程都在执行任务时，任务会被放入等待队列中。当队列满了，线程池会创建更多的线程（最多到达最大线程数）。
        // 如果所有线程都在执行任务，而且队列已满，线程池会拒绝新的任务执行。
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setCorePoolSize(5);
        pool.setMaxPoolSize(10);
        pool.setQueueCapacity(50);
        pool.setKeepAliveSeconds(60);
        pool.setThreadNamePrefix("MyThreadPoolTaskExecutor-");
        pool.setRejectedExecutionHandler((runnable, e) -> {
            throw new SecurityException("This threadPool is busy!");
        });
        pool.initialize();

        // 生成整数,转换成 Integer 类型收集成 List
        List<Integer> list = IntStream.range(0, 50).boxed().collect(Collectors.toList());
        System.out.println("数组生成如下："); System.out.println(list);System.out.println("====================================================================");
        CompletableFuture.allOf(
                list.stream().map(
                        o -> CompletableFuture.runAsync(() -> {
                            System.out.println("当前任务处理为" + o + ",当前线程：" + Thread.currentThread().getName());
                        }, pool).exceptionally(throwable -> {
                            throw new RuntimeException(throwable.getMessage());
                        })).toArray(CompletableFuture[]::new)).join();
        // 关闭线程池
        pool.shutdown();
        System.out.println("所有任务执行完毕，程序结束。");
    }




}
